from info import db, constants
from info.models import Category, News
from info.utils.image_storage import storage
from info.utils.response_code import RET
from . import profile_blue
from flask import render_template, g, redirect, request, jsonify, current_app, session
from info.utils.common import user_login_data


# 用户发布新闻列表
@profile_blue.route('/news_list')
@user_login_data
def user_news_list():

    # 查询数据 需要自己的id
    page = request.args.get('p', 1)
    try:
        page = int(page)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg='页码错误')

    user = g.user
    # 为防止查询失败报错
    news_model_list = []
    current_page = 1
    total_page = 1
    try:
        paginates = News.query.filter(News.user_id == user.id).paginate(page, constants.USER_COLLECTION_MAX_NEWS, False)
        news_model_list = paginates.items
        # 当前页码
        current_page = paginates.page
        # 总页码
        total_page = paginates.pages
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='查询失败')

    news_dict_li = []
    for news in news_model_list:
        news_dict_li.append(news.to_review_dict())

    data = {
        "news_list": news_dict_li,
        "current_page": current_page,
        "total_page": total_page
    }

    return render_template('news/user_news_list.html', data=data)


# 新闻发布的视图函数
@profile_blue.route('/news_release', methods=["GET", "POST"])
@user_login_data
def user_news_release():
    if request.method == "GET":
        # 查询分类数据 将模板转换为字典返回
        try:
            categories = Category.query.all()
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.DBERR, errmsg='查询失败')
        category_dict_li = []
        for category in categories:
            category_dict_li.append(category.to_dict())

        # 去掉名为最新的数据
        category_dict_li.pop(0)
        data = {
            'categories': category_dict_li
        }
        return render_template('news/user_news_release.html', data=data)

    # POST 请求
        # 1. 获取要提交的数据
    title = request.form.get("title")
    source = "个人发布"
    # 新闻摘要
    digest = request.form.get("digest")
    content = request.form.get("content")
    index_image = request.files.get("index_image")
    category_id = request.form.get("category_id")
    # 1.1 判断数据是否有值
    if not all([title, source, digest, content, index_image, category_id]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数有误")

    # 对分类id 进义 查询数据库是否有这个id
    # category_id = int(category_id)
    # try:
    #     cate_
    # except Exception as e:
    #
    #     current_app.logger.error(e)
    #     return jsonify(errno=RET.DBERR, errmsg='查询失败')

    # 获取图片
    try:
        index_image_data = index_image.read()
        image_file_name = storage(index_image_data)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.THIRDERR, errmsg='上传图片失败')

    # 添加模型到数据库
    news = News()
    news.title = title
    news.digest = digest
    news.source = source
    news.content = content
    news.index_image_url = constants.QINIU_DOMIN_PREFIX + image_file_name
    news.category_id = category_id
    news.user_id = g.user.id

    # 1代表待审核状态 1 代表未通过
    news.status = 1

    try:
        db.session.add(news)
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='查询失败')

    return jsonify(errno=RET.OK, errmsg='成功')


# 用户新闻收藏
@profile_blue.route('/collection')
@user_login_data
def user_collection():
    # 获取页数
    p = request.args.get("p", 1)
    try:
        p = int(p)
    except Exception as e:
        current_app.logger.error(e)
        p = 1
    user = g.user
    collections = []
    current_page = 1
    total_page = 1
    try:
        # 进行分页数据查询
        paginate = user.collection_news.paginate(p, constants.USER_COLLECTION_MAX_NEWS, False)
        # 获取分页数据
        collections = paginate.items
        # 获取当前页
        current_page = paginate.page
        # 获取总页数
        total_page = paginate.pages
    except Exception as e:
        current_app.logger.error(e)

    # 收藏列表
    collection_dict_li = []
    for news in collections:
        collection_dict_li.append(news.to_basic_dict())

    data = {"total_page": total_page,
            "current_page": current_page,
            "collections": collection_dict_li}
    return render_template('news/user_collection.html', data=data)


# 修改用户密码的接口
@profile_blue.route('/pass_info', methods=["GET", "POST"])
@user_login_data
def pass_info():
    if request.method == "GET":
        return render_template('news/user_pass_info.html')

    # 获取参数
    old_password = request.json.get('old_password')
    new_password = request.json.get('new_password')
    # 校验参数
    if not all([old_password, new_password]):
        return jsonify(errno=RET.PARAMERR, errmsg='参数不全')
    # 逻辑处理部分
    # 获取原始密码对比
    user = g.user
    if not user.check_password(old_password):
        return jsonify(errno=RET.PWDERR, errmsg='原密码填入错误')
    user.password = new_password
    # 还要判断新旧密码是否一样
    # 正常要手动提交
    # db.session
    return jsonify(errno=RET.OK, errmsg='修改密码成功')


# 修改头像
@profile_blue.route('/pic_info', methods=["GET", "POST"])
@user_login_data
def pic_info():
    user = g.user
    if request.method == "GET":
        return render_template('news/user_pic_info.html', data={"user": user.to_dict()})
    # 上传图像
    try:
        avatar = request.files.get('avatar').read()

    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg='读取文件失败')
    try:
        key = storage(avatar)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg='上传文件失败')
    user.avatar_url = key
    return jsonify(errno=RET.OK, errmsg='上传图像成功', data={'avatar_url': constants.QINIU_DOMIN_PREFIX + key})


# 修改昵称 个性签名 性别的视图函数
@profile_blue.route('/base_info', methods=["GET", "POST"])
@user_login_data
def base_info():
    # 不同的请求方式做不同的事
    # get获取数据 post 修改数据
    if request.method == "GET":
        data = {
            'user': g.user.to_dict()
        }
        return render_template('news/user_base_info.html', data=data)
    # post请求
    # 1 获取传入的参数
    nick_name = request.json.get('nick_name')
    signature = request.json.get('signature')
    gender = request.json.get('gender')
    # 2 校验参数
    if not all([nick_name, signature, gender]):
        return jsonify(errno=RET.PARAMERR, errmsg='参数不全')
    if gender not in ['MAN', 'WOMAN']:
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')
    # 3 修改用户的数据
    user = g.user
    user.gender = gender
    user.nick_name = nick_name
    user.signature = signature

    try:
        db.session.add(user)
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='提交失败')
    # 更新session的信息
    session['nick_name'] = nick_name

    # 返回数据
    return jsonify(errno=RET.OK, errmsg='成功')


@profile_blue.route('/info')
@user_login_data
def user_info():
    # 判断用户是否登录
    user = g.user
    # 如果不存在返回首页 实际开发过程中跳转登录页面
    if not user:
        return redirect('/')
    data = {
        'user': user.to_dict()
    }

    return render_template('news/user.html', data=data)
